﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Threading;
using System.Windows.Media.Imaging;
using System.Windows.Browser;

namespace SilverlightPlayer
{
    public partial class Page : UserControl
    {
        DispatcherTimer controlsHideTimer = new DispatcherTimer() { Interval = TimeSpan.FromSeconds(5) };
        DispatcherTimer progressTimer = new DispatcherTimer() { Interval = TimeSpan.FromMilliseconds(250) };
        DispatcherTimer playlistHideTimer = new DispatcherTimer() { Interval = TimeSpan.FromSeconds(3) };

        ProgressIndicator progress = new ProgressIndicator();
        TrackListManager manager = new TrackListManager();
        bool AudioMode = false;
        public Page()
        {
            InitializeComponent();

            manager.TracksFetched += new EventHandler(manager_TracksFetched);

            mediaSource.MediaOpened += new RoutedEventHandler(mediaSource_MediaOpened);
            mediaSource.MediaEnded += new RoutedEventHandler(mediaSource_MediaEnded);
            mediaSource.MediaFailed += new EventHandler<ExceptionRoutedEventArgs>(mediaSource_MediaFailed);

            if (!String.IsNullOrEmpty(App.AudioMode) && App.AudioMode != "false")
            {
                VisualStateManager.GoToState(this, "Audio", false);
                AudioMode = true;

                HtmlElement mysilverlightdiv = HtmlPage.Plugin;
                if (mysilverlightdiv != null)
                {
                    mysilverlightdiv.SetAttribute("height", "32");
                }
            }

            

            if (!String.IsNullOrEmpty(App.StreamUri))
            {
                mediaSource.Source = new Uri(App.StreamUri, UriKind.RelativeOrAbsolute);
                if(!AudioMode) VisualStateManager.GoToState(this, "Streaming", false);
            }
            else VisualStateManager.GoToState(this, "Playlist", false);

            if (!String.IsNullOrEmpty(App.LogoUri) && !AudioMode)
            {
                
                imgLogo.Source = new BitmapImage(new Uri(App.LogoUri, UriKind.RelativeOrAbsolute));
            }


            if (!string.IsNullOrEmpty(App.AutoPlay) && App.AutoPlay != "false") mediaSource.AutoPlay = true;

            controls.DataContext = progress;
            mediaSource.Volume = 0.8;
            volumeSlider.Value = mediaSource.Volume;

            playlistHideTimer.Start();
            controlsHideTimer.Start();


            playList.TrackIsSelected += OnTrackIsSelected;
            progressTimer.Tick += OnUpdateTimerProgress;
            controlsHideTimer.Tick += OnControlsHideTimerTick;
            playlistHideTimer.Tick += OnPlaylistHideTimer;


             VisualStateManager.GoToState(this, "ControlsVisible", true);
        }



        void manager_TracksFetched(object sender, EventArgs e)
        {
            foreach (Track t in manager.Tracks) playList.TrackList.Add(t);
            playList.play();
            if (playList.CurrentPlayingTrackIndex == 0) btnPrevious.IsEnabled = false; else btnPrevious.IsEnabled = true;
            if (playList.CurrentPlayingTrackIndex == playList.TrackList.Count - 1) btnNext.IsEnabled = false; else btnNext.IsEnabled = true;
        }

        int videosLoaded = 0;

        void OnTrackIsSelected(object sender, TrackIsSelectedEventArgs e)
        {
            videosLoaded++;
            btnPlayPause.IsChecked = false;
            if (!string.IsNullOrEmpty(App.AutoPlay) && App.AutoPlay == "false" && videosLoaded <= 1) mediaSource.AutoPlay = false; else mediaSource.AutoPlay = true;
            mediaSource.Source = new Uri(e.TrackSelected.Location, UriKind.RelativeOrAbsolute);
            if (playList.CurrentPlayingTrackIndex == 0) btnPrevious.IsEnabled = false; else btnPrevious.IsEnabled = true;
            if (playList.CurrentPlayingTrackIndex == playList.TrackList.Count - 1) btnNext.IsEnabled = false; else btnNext.IsEnabled = true;
            btnPlayPause.IsChecked = true;
        }

        void mediaSource_MediaFailed(object sender, ExceptionRoutedEventArgs e)
        {
            progressTimer.Stop();
        }

        void mediaSource_MediaEnded(object sender, RoutedEventArgs e)
        {
            progressTimer.Stop();
        }

        void mediaSource_MediaOpened(object sender, RoutedEventArgs e)
        {
            progressTimer.Start();

        }

        void OnUpdateTimerProgress(object sender, EventArgs e)
        {
            if (mediaSource.CurrentState == MediaElementState.Playing)
            {
                progress.ElapsedTime = mediaSource.Position.TotalMinutes.ToString("00") + ":" + mediaSource.Position.Seconds.ToString("00");
                progress.TotalTime = mediaSource.NaturalDuration.TimeSpan.TotalMinutes.ToString("00") + ":" + mediaSource.NaturalDuration.TimeSpan.Seconds.ToString("00");

                progressSlider.ValueChanged -= progressSlider_ValueChanged;
                double percent = ((double)mediaSource.Position.TotalMilliseconds / (double)mediaSource.NaturalDuration.TimeSpan.TotalMilliseconds);
                progressSlider.Value = percent;
                progressSlider.ValueChanged += progressSlider_ValueChanged;
            }
        }


        private void progressSlider_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
            if (progressSlider.IsEnabled)
            {
                double percent = progressSlider.Value;
                mediaSource.Position = TimeSpan.FromMilliseconds(percent * (double)mediaSource.NaturalDuration.TimeSpan.TotalMilliseconds);

            }
        }




        private void mediaSource_CurrentStateChanged(object sender, EventArgs e)
        {

                switch (mediaSource.CurrentState)
                {
                    case MediaElementState.Buffering:
                        VisualStateManager.GoToState(this, "Buffering", false);
                        break;
                    case MediaElementState.Playing:
                        VisualStateManager.GoToState(this, "Playing", false);
                        btnPlayPause.IsChecked = true;
                        break;
                    case MediaElementState.Paused:
                        VisualStateManager.GoToState(this, "Stopped", false);
                        btnPlayPause.IsChecked = false;
                        break;
                    case MediaElementState.Stopped:
                        VisualStateManager.GoToState(this, "Stopped", false);
                        btnPlayPause.IsChecked = false;
                        break;
                    case MediaElementState.Opening:
                        VisualStateManager.GoToState(this, "Buffering", false);
                        btnPlayPause.IsChecked = false;
                        break;


                }
           
        }

        private void mediaSource_BufferingProgressChanged(object sender, RoutedEventArgs e)
        {
            bufferIndicator.Percent = Convert.ToInt32(mediaSource.BufferingProgress * 100);
        }

        private void Slider_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
            mediaSource.Volume = volumeSlider.Value;
        }

        private void OnbtnPlayPause(object sender, RoutedEventArgs e)
        {
            if (btnPlayPause.IsChecked == true)
            {
                mediaSource.Play();
            }
            else
            {
                mediaSource.Pause();
            }
        }

        private void btnFullScreen_Click(object sender, RoutedEventArgs e)
        {
            if (btnFullScreen.IsChecked == true)
            {
                Application.Current.Host.Content.IsFullScreen = true;
            }
            else
            {
                Application.Current.Host.Content.IsFullScreen = false;
            }
        }

        private void btnSoundOnOff_Click(object sender, RoutedEventArgs e)
        {

            if (btnSoundOnOff.IsChecked == true)
            {
                mediaSource.IsMuted = true;
            }
            else
            {
                mediaSource.IsMuted = false;
            }
        }

        private void btnNext_Click(object sender, RoutedEventArgs e)
        {
            playList.CurrentPlayingTrackIndex++;
        }

        private void btnPrevious_Click(object sender, RoutedEventArgs e)
        {
            playList.CurrentPlayingTrackIndex--;

        }

        private void OnPlayListShow(object sender, MouseEventArgs e)
        {
            ShowPlaylist();
            playlistHideTimer.Start();

        }

        private void OnStartPlaylistHide(object sender, MouseEventArgs e)
        {
            playlistHideTimer.Start();
        }



        void OnPlaylistHideTimer(object sender, EventArgs e)
        {
            HidePlaylist();
            playlistHideTimer.Stop();
        }

        void OnControlsHideTimerTick(object sender, EventArgs e)
        {
            HideControls();
            controlsHideTimer.Stop();
        }

        private void Grid_MouseMove(object sender, MouseEventArgs e)
        {
            ShowControls();
            controlsHideTimer.Start();
        }

        private void Grid_MouseEnter(object sender, MouseEventArgs e)
        {
            ShowControls();
            controlsHideTimer.Start();
        }


        private void ShowControls()
        {
            if (!AudioMode)
            {
                VisualStateManager.GoToState(this, "ControlsVisible", true);
            }
        }

        private void HideControls()
        {
            if (!AudioMode)
            {
                VisualStateManager.GoToState(this, "ControlsHidden", true);
            }
        }

        private void ShowPlaylist()
        {
            if (!AudioMode)
            {
                VisualStateManager.GoToState(this, "PlaylistVisible", true);
            }
        }

        private void HidePlaylist()
        {
            if (!AudioMode)
            {
                VisualStateManager.GoToState(this, "PlaylistHidden", true);
            }
        }

        private void border_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            btnPlayPause.IsChecked = true;
            mediaSource.Play();
        }



    }
}
